package com.marlowe.asyouknow.service;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @program: as-you-know
 * @description: 查询图片服务类
 * @author: Marlowe
 * @create: 2020-12-22 16:58
 **/
@Service
public class PicturesService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 获取这些数据实现分页搜索功能
     *
     * @return
     */
    public List<Map<String, Object>> searchPage(String keywords, int pageNo, int pageSize) throws IOException {
        if (pageNo <= 1) {
            pageNo = 1;
        }
        // 条件搜索
        SearchRequest searchRequest = new SearchRequest("pictures");
        System.out.println(searchRequest);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //matchQuery：会将搜索词分词，再与目标查询字段进行匹配，若分词中的任意一个词与目标字段匹配上，则可查询到。
        MatchQueryBuilder termQueryBuilder = QueryBuilders.matchQuery("title", keywords);
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 执行搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(searchResponse);

        // 解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            list.add(documentFields.getSourceAsMap());
        }
        return list;
    }

    /**
     * 获取这些数据实现分页搜索高亮功能
     *
     * @return
     */
    public List<Map<String, Object>> searchPageHighlightBuilder(String keywords, int pageNo, int pageSize) throws IOException {
        System.out.println("请求成功！");
        System.out.println("查询的关键词:" + keywords);
        if (pageNo <= 1) {
            pageNo = 1;
        }
        // 条件搜索
        SearchRequest searchRequest = new SearchRequest("pictures");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        // 分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);

        //精准匹配
//        matchQuery：会将搜索词分词，再与目标查询字段进行匹配，若分词中的任意一个词与目标字段匹配上，则可查询到。
        MatchQueryBuilder termQueryBuilder = QueryBuilders.matchQuery("title", keywords);
        sourceBuilder.query(termQueryBuilder);
        SearchSourceBuilder timeout = sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        // 高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        // 多个高亮显示
        highlightBuilder.requireFieldMatch(false);
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);

        // 执行搜索
        SearchRequest source = searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {

            // 获取高亮的字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();

            // 解析高亮的字段
            if (title != null) {
                Text[] fragments = title.fragments();
                String titleNew = "";
                for (Text text : fragments) {
                    titleNew += text;
                }
                // 高亮字段替换掉原来的内容即可
                sourceAsMap.put("title", titleNew);
            }
            list.add(sourceAsMap);
        }
        System.out.println("结果个数：" + list.size());
        return list;
    }

    /**
     * 搜索建议
     *
     * @return
     */
    public List<Map<String, Object>> searchSuggestion(String keywords) throws IOException {
        System.out.println("请求成功！");
        System.out.println("查询的关键词:" + keywords);
        // 1.新建查询请求对象
        SearchRequest searchRequest = new SearchRequest("pictures");

        // 2.查询条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 查询的数量
        sourceBuilder.size(50);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //前缀匹配
        MatchPhrasePrefixQueryBuilder termQueryBuilder = QueryBuilders.matchPhrasePrefixQuery("title", keywords);


        // 3.将查询条件添加到sourceBuilder中
        sourceBuilder.query(termQueryBuilder);

        // 将sourceBuilder放入查询中
        searchRequest.source(sourceBuilder);

        // 4.执行搜索
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        // 解析结果
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {

            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            String title = (String) sourceAsMap.get("title");
            if (keywords != null && title.substring(0, keywords.length()).equals(keywords)) {
                System.out.println("title:" + title);
                Map<String, Object> resMap = new HashMap<>();
                resMap.put("title", new String(title));
                list.add(resMap);
            }
        }
        // 取出推荐的前10条
        List<Map<String, Object>> resList = new ArrayList<>();
        int count = 0;
        for (Map<String, Object> item : list) {
            resList.add(item);
            count++;
            if (count == 10) {
                break;
            }
        }
        Set<Map<String, Object>> set = new HashSet<>(resList);
        System.out.println("结果个数：" + resList.size());
        return new ArrayList<>(set);
    }
}
